package com.liaoye.hellocustomview.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;

import androidx.appcompat.widget.AppCompatImageView;

import com.liaoye.hellocustomview.R;

public class WatermarkImageView extends AppCompatImageView {
    private Bitmap mBitmap;
    private final String TAG = WatermarkImageView.class.getSimpleName();

    public WatermarkImageView(Context context) {
        super(context);
    }

    public WatermarkImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WatermarkImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        Log.i(TAG, "onFinishInflate: ");
        if (mBitmap == null) {
            mBitmap = createWaterBitmap();
            invalidate();
        }
    }


    private Bitmap createWaterBitmap() {
        BitmapDrawable bd = (BitmapDrawable) this.getDrawable();
        Bitmap srcBitmap = bd.getBitmap();
        int width = srcBitmap.getWidth();
        int height = srcBitmap.getHeight();

        Bitmap watermarkBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.watermark);
        int wWidth = watermarkBitmap.getWidth();
        int wHeight = watermarkBitmap.getHeight();

        Bitmap newBm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBm);
        canvas.drawBitmap(srcBitmap, 0, 0, null);
        int left = width - wWidth;
        int top = height - wHeight;
        canvas.drawBitmap(watermarkBitmap, left, top, null);
        return newBm;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mBitmap != null) {
            canvas.drawBitmap(mBitmap, 0, 0, null);
        }

    }
}
